package org.springbus.ff.log;

import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.AttributedString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springbus.ff.util.CmdCallBack;

public class FFlogCallBack implements CmdCallBack {
    private static final Logger logger = LoggerFactory.getLogger(FFlogCallBack.class);

    Terminal terminal = null;

    private  int width=100;

    public  FFlogCallBack() {
        try {
            terminal = TerminalBuilder.terminal();
        } catch (Exception ignored) {
        }
    }

    @Override
    public void onstart() {
        logger.info("ffmepg start");
    }

    @Override
    public void onProgress(String log) {
        display(log);
    }

    public void display(String line) {
        if (terminal != null) {
            terminal.writer().println(toColor(line));
            terminal.flush();
        }
    }

    private String toColor(String line){
     return    AttributedString.fromAnsi("\u001B[32m\"" + line + "\u001B[0m")
                .toAnsi(terminal);
    }
    private String toErrorColor(String line){
        return    AttributedString.fromAnsi("\u001B[31m\"" + line + "\u001B[0m")
                .toAnsi(terminal);
    }

    @Override
    public void onEnd(int code) {
        logger.info(">>ffmpeg exit with code ={}",code);
        try {
            if(terminal!=null) {
                if(code==0){
                    terminal.writer().println(toColor("ffmpeg execute end success"));
                }else{
                    terminal.writer().println(toErrorColor("ffmpeg execute end with error"));
                }
                terminal.flush();
                terminal.close();
            }
        }catch (Exception ignored){}
    }

    @Override
    public void onError(Exception e) {
        logger.error("{}",e);
    }
}
